package cn.mvcjava.controller;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import javax.jws.WebService;
import javax.management.RuntimeErrorException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.mvcjava.dao.FactoryDao;
import cn.mvcjava.model.User;
import cn.mvcjava.service.FactoryService;
import cn.mvcjava.service.UserService;


@WebServlet(urlPatterns = { "*.udo" })
public class UserController extends HttpServlet {
	 
	/**
	 * 序列化机制。
	 */
	private static final long serialVersionUID = 1L;

     UserService  userService= FactoryService.getUserService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 doPost(req, resp);
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub 
//		 System.out.println(req.getServletPath());
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		 String  mn = req.getServletPath();
		 mn =mn.substring(1);
	     mn =mn.substring(0,mn.length()-4);
	     resp.getWriter().print(mn);
	     
	     try {
			Method method = this.getClass().getDeclaredMethod(mn, HttpServletRequest.class,HttpServletResponse.class);
			method.invoke(this,req,resp);
		}   catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	} 
	
	private  void  add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		 User user =new User();
		 user.setUsername(req.getParameter("username"));
		 user.setPassword(req.getParameter("password"));
		 user.setAdress(req.getParameter("adress"));
		 user.setPhone(req.getParameter("phone")); 
		 int rows =  userService.save(user);
		 if(rows > 0) {
			 resp.sendRedirect(req.getContextPath()+"/index.jsp");
		 }else{ 
			 resp.sendRedirect(req.getContextPath()+"/error.jsp");
		 }
	} 
	private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		  
		 String username= req.getParameter("username");
		 String adress= req.getParameter("adress");
		 String phone= req.getParameter("phone");
		 // 防止sql 注入的风险。
//		  phone = phone.replaceAll("[`~!@#$%^&*()=|{}':;',\\[\\].<>/?~!@#￥......&*（）&mdash;-|{}【】‘；：”“'。，、？]", "");
		  List<User> list =  userService.query(username,adress,phone);
		  req.setAttribute("userlist", list);
		  req.getRequestDispatcher("/index.jsp").forward(req, resp);
	}
	 
	private  void  delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		
		System.out.println(id+"kongshiaho");
		int rows = userService.deletectUserById(id);
		 if(rows > 0) {
			 resp.sendRedirect(req.getContextPath()+"/index.jsp");
		 }else{ 
			 resp.sendRedirect(req.getContextPath()+"/error.jsp");
		 }
		
		
	}
	
	private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		User  user = userService.get(id);
		req.setAttribute("user", user);
        req.getRequestDispatcher("/update.jsp").forward(req, resp);	
	}
	
	public void  updatedo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id")); 
		User user = userService.get(id); 
		String xusername = user.getUsername();
		String yusernameString = req.getParameter("username"); 
		long cout = userService.getCountName(yusernameString); 
		if(!xusername.equals(yusernameString) && cout > 0) {  //新名字和老名字一样。 数据库中找到相同的类型。
			 req.setAttribute("note", xusername+";，这个名字已被占用，请换个名字！");
			 req.getRequestDispatcher("/update.udo?id="+id).forward(req, resp);
			 return;
		} 
		user.setUsername(req.getParameter("username"));
		user.setPassword(req.getParameter("password"));
		user.setAdress(req.getParameter("adress"));
		user.setPhone(req.getParameter("phone")); 
		int rows =  userService.UpdateUserById(user); 
		 if(rows > 0){
			 resp.sendRedirect(req.getContextPath()+"/index.jsp");
		 }else{ 
			 resp.sendRedirect(req.getContextPath()+"/error.jsp");
		 }
		 
	}
	
	
	

}
